#include "child.h"
#include<QWidget>
#include<QMessageBox>
#include<QFile>
#include<QTextCodec>
#include<QFileDialog>
#include<QTextDocumentWriter>
#include<QFileInfo>
#include<QTextList>
#include<QTextDocument>

child::child() {
    setAttribute(Qt::WA_DeleteOnClose);//关闭时销毁
    isUntitled = true;
}
void child::newFile()
{
    //新建文件
    static int sequenceNumber = 1;
    isUntitled = true;
    curFile = tr("新建文档 %1").arg(sequenceNumber++);
    setWindowTitle(curFile);//设置窗口标题
}
//打开本地文件
bool child::loadFile(const QString &fileName)
{
    if(!fileName.isEmpty())
    {
        if(!QFile::exists(fileName))
        {
            return false;
        }

        QFile file(fileName);//没问题
        if (!file.open(QIODevice::ReadOnly))
        {
            qDebug() << "Failed to open file:" << file.errorString();
            return -1; // 处理错误
        }
        QByteArray data = file.readAll();//
        QTextCodec *codec = Qt::codecForHtml(data);
        QString str = codec->toUnicode(data);

        if(Qt::mightBeRichText(str))
        {
            this->setHtml(str);
        }
        else
        {
            qDebug()<<"if(Qt::mightBeRichText(str))else";
            str = QString(data);
            //QString cstr = "这里是测试";
            this->setPlainText(str);
        }
        setCurrentFile(fileName);
        connect(document(), &QTextDocument::contentsChanged, this, &child::documentWasModified);
        //connect(document(),SIGNAL(contentsChanged()),this,SLOT(documentWasModified));
    }
    return true;
}

bool child::save()
{
    if(isUntitled)
    {
        return saveAs();
    }
    else
    {
        return saveFile(curFile);
    }
}

bool child::saveAs()
{
    QString fileName = QFileDialog::getSaveFileName(this,tr("另存为"),curFile,tr("HTML 文档(*.html *.html);;所有文件 (*.*)"));
    if(fileName.isEmpty())
    {
        return false;
    }
    return saveFile(fileName);
}

bool child::saveFile(QString fileName)
{
    if(!(fileName.endsWith(".htm",Qt::CaseInsensitive) || fileName.endsWith(".html",Qt::CaseInsensitive)))
    {
        fileName += ".html";
    }

    QTextDocumentWriter writer(fileName);
    bool success = writer.write(this->document());
    if(success)
    {
        setCurrentFile(fileName);
    }

    return success;
}

void child::closeEvent(QCloseEvent *event)
{
    if(maybeSave())
    {
        event->accept();
    }
    else
    {
        event->ignore();
    }
}

void child::documentWasModified()
{
    setWindowModified(document()->isModified());
}

void child::setCurrentFile(const QString &fileName)
{
    curFile = QFileInfo(fileName).canonicalFilePath();
    isUntitled = false;
    document()->setModified(false);
    setWindowModified(false);
    setWindowTitle(userFriendlyCurrentfile() + "[*]");
}

bool child::maybeSave()
{
    if(!document()->isModified())
    {
        return true;
    }

    QMessageBox::StandardButton ret;
    ret = QMessageBox::warning(this,tr("Qt Word"),tr("文件'%1'已经被修改，是否保存?").arg(userFriendlyCurrentfile()),
                               QMessageBox::Save|QMessageBox::Discard|QMessageBox::Cancel);
    if(QMessageBox::Save == ret)
    {
        return save();
    }
    else if(QMessageBox::Cancel == ret)
    {
        return false;
    }

    return true;
}

QString child::userFriendlyCurrentfile()
{
    return strippedName(curFile);
}

QString child::strippedName(const QString &fullFileName)
{
    return QFileInfo(fullFileName).fileName();
}

void child::mergeFormationOnWordOrSelection(const QTextCharFormat &format)
{
    QTextCursor cursor = this->textCursor();

    if(!cursor.hasSelection())
    {
        cursor.select(QTextCursor::WordUnderCursor);
    }
    cursor.mergeCharFormat(format);
    this->mergeCurrentCharFormat(format);
}
//设置段落格式
void child::setAlign(int align)
{
    if(1 == align)
    {
        this->setAcceptDrops(Qt::AlignLeft | Qt::AlignAbsolute);//水平左对齐
    }
    else if(2 == align)
    {
        this->setAlignment(Qt::AlignCenter);//水平居中
    }
    else if(3 == align)
    {
        this->setAlignment(Qt::AlignRight | Qt::AlignAbsolute);//水平靠右
    }
    else if(4 == align)
    {
        this->setAlignment(Qt::AlignJustify);//两端对齐
    }
}
//设置标号样式
void child::setStyle(int style)
{
    QTextCursor cursor = this->textCursor();

    if(0 != style)
    {
        QTextListFormat::Style stylename = QTextListFormat::ListDisc;//
        switch (style) {
        case 1:
            stylename = QTextListFormat::ListDisc;
            break;
        case 2:
            stylename = QTextListFormat::ListCircle;
            break;
        case 3:
            stylename = QTextListFormat::ListSquare;
            break;
        case 4:
            stylename = QTextListFormat::ListDecimal;
            break;
        case 5:
            stylename = QTextListFormat::ListLowerAlpha;
            break;
        case 6:
            stylename = QTextListFormat::ListUpperAlpha;
            break;
        case 7:
            stylename = QTextListFormat::ListLowerRoman;
            break;
        case 8:
            stylename = QTextListFormat::ListUpperRoman;
            break;
        default:
            break;
        }

        cursor.beginEditBlock();
        QTextBlockFormat blockfmt = cursor.blockFormat();
        QTextListFormat listfmt;
        if(cursor.currentList())
        {
            listfmt = cursor.currentList()->format();
        }
        else
        {
            listfmt.setIndent(blockfmt.indent() + 1);
            blockfmt.setIndent(0);
            cursor.setBlockFormat(blockfmt);
        }

        listfmt.setStyle(stylename);
        cursor.createList(listfmt);
        cursor.endEditBlock();
    }
    else
    {
        QTextBlockFormat bfmt;
        bfmt.setObjectIndex(-1);
        cursor.mergeBlockFormat(bfmt);
    }
}
























